package com.code.leetcode.idea;

public class LeetCodeIdea008 {
    public static void main(String[] args) {
        LeetCodeIdea008 leetCodeIdea008 = new LeetCodeIdea008();
        int res = leetCodeIdea008.myAtoi("-2147483649");
        System.out.println(res);
//        System.out.println(Integer.MIN_VALUE);
    }

    public int myAtoi(String str) {
        int length = str.length();
        char[] cc = str.toCharArray();

        int index = 0;
        while(index < length && cc[index] == ' ') {
            index++;
        }
        if (index == length) {
            return 0;
        }

        int sign = 1;
        if (cc[index] == '+') {
            index++;
        } else if(cc[index] == '-') {
            index ++;
            sign = -1;
        }
        int res = 0;
        while (index <length) {
            char curChar = cc[index];
            if (curChar > '9' || curChar < '0' ) {
                break;
            }
            if (res > Integer.MAX_VALUE/10 || (res == Integer.MAX_VALUE/10  && (curChar - '0') > Integer.MAX_VALUE % 10)) {
                return Integer.MAX_VALUE;
            }
            if (res < Integer.MIN_VALUE/10 || (res == Integer.MIN_VALUE/10 && (curChar - '0') > -(Integer.MIN_VALUE % 10) )) {
                return Integer.MIN_VALUE;
            }
            res =  res * 10 + sign * (curChar - '0');
            index++;
        }
        return res;
    }

}
